package com.dgwcode.union.sublclass;

import java.util.List;

import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import utils.HibernateUtils;

public class HibernateTest {
	
	private Session session;

	@Before
	public void before() {
		session = HibernateUtils.getSession();
		session.beginTransaction();
	}
	/**
	 * 优点:
	 * 1. 无需使用辨别者列.
	 * 2. 子类独有的字段能添加非空约束.
	 * 
	 * 缺点:
	 * 1. 存在冗余的字段
	 * 2. 若更新父表的字段, 则更新的效率较低
	 */
	/**
	 * 查询:
	 * 1. 查询父类记录, 需要使用联合union查询全部数据表
	 * 2. 对于子类记录, 只需要查询子表数据
	 */
	@Test
	public void testGET() {
		/*Person person = session.get(Person.class, 1);
		
		System.out.println(person.getName());
		
		//具有序号的情况下，hibernate自动维护属性列
		Worker worker = session.get(Worker.class, 3);
		
		System.out.println(worker.getCompany());*/
		
		//默认
		List list = session.createQuery("FROM Person").list();
		
		//自动加上类型
		List list2 = session.createQuery("FROM Student").list();
		System.out.println(list.size());
		System.out.println(list2.size());
		
	}
	
	/**
	 * 插入操作: 
	 * 1. 对于子类对象只需把记录插入到一张数据表中.
	 */
	@Test
	public void testUnionSubClass() {
		Person person = new Person();
		
		person.setName("DGW");
		person.setAge(25);
		
		session.save(person);
		
		Student student = new Student();
		student.setName("DGW");
		student.setAge(25);
		student.setSchool("WSY");
		
		
		//如果不写子类属性，并不会自动映射父类属性
		//session.save(person);
		session.save(student);
		
		Worker worker = new Worker();
		worker.setName("DGW");
		worker.setAge(25);
		worker.setCompany("baidu");
		
		//session.save(worker);
	}
	
	@After
	public void after() {
		session.getTransaction().commit();
		session.close();
	}

}
